﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Kinect;
using System.Windows;


namespace DetectingKinectSencor
{
    /// <summary>
    /// The following class was provided by the book 
    /// Microsoft.Press.Programming.with.the.Kinect.for.Windows.Software.Development.Kit.Sep.2012
    /// </summary>
    class RecordColorStream
    {
        private bool DEBUGon = MainWindow.DEBUGrecordColorStream;

        DateTime referenceTime;
        readonly BinaryWriter writer;

        //Constuctor of RecordColorStream
        internal RecordColorStream(BinaryWriter writer)
        {
            this.writer = writer;
            referenceTime = DateTime.Now;
        }


        /// <summary>
        /// Method thad records the color stream
        /// </summary>

        public void Record(ColorImageFrame frame)
        {
            // Write the hdeader, this is importat to distinguish between the three different streams
            // (at the end one file which includes the three streams)
            writer.Write((int)DetectingKinectSencor.RecordStreams.KinectRecordOptions.Color);
            
            // Writing the data
            // Timespan is important, because a reference time is needed. Each recorder must keep a reference time
            // variable and add it to the saved stream to allow the player to reproduce the data at the same frequency
            // Identify the difference between the time now and the time of the last frame            
            TimeSpan timeSpan = DateTime.Now.Subtract(referenceTime);

            if(DEBUGon)
                Console.WriteLine("color: Record: timeSpan: " + timeSpan.TotalMilliseconds);

            // Set now to the new referenceTime
            referenceTime = DateTime.Now;

            writer.Write((long)timeSpan.TotalMilliseconds);

          
            //Write number of bytes per pixel
            writer.Write(frame.BytesPerPixel);

            //Write the frame format
            writer.Write((int)frame.Format);

            //Write the with and height of the frame
            writer.Write(frame.Width);
            writer.Write(frame.Height);

            //Write the frame number
            writer.Write(frame.FrameNumber);

            if (DEBUGon)
                Console.WriteLine("color: Record: FrameNumber: " + frame.FrameNumber);
            
            // Write the pixel lengh of the frame
            writer.Write(frame.PixelDataLength);

            // Create a new object in which the pixels of the frame are copied to
            byte[] bytes = new byte[frame.PixelDataLength];
            frame.CopyPixelDataTo(bytes);

            // Write the actual bytes of the frame
            writer.Write(bytes);
        }
    }
}
